package com.cnap.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.util.ObjectUtil;
import com.cnap.model.exception.JsonException;
import com.cnap.model.indicator.IndicatorExportModel;
import com.cnap.model.indicator.QueryIndicatorParam;
import com.cnap.service.ExportService;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <类说明>
 *
 * @author xc
 **/
@Service
public class ExportServiceImpl implements ExportService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExportServiceImpl.class);
    private static final int PAGE_SIZE = 1000;

    private final IndicatorExportServer indicatorExportServer;

    @Autowired
    public ExportServiceImpl(IndicatorExportServer indicatorExportServer) {
        this.indicatorExportServer = indicatorExportServer;
    }

    /**
     * 导出指标
     *
     * @param request  请求
     * @param response 响应
     */
    @Override
    public void exportIndicator(HttpServletRequest request, HttpServletResponse response) {
        // 构建查询参数
        String indicatorType = request.getParameter("indicatorType");
        String category = request.getParameter("category");
        String indicatorName = request.getParameter("indicatorName");

        // 如果没有查询参数，则配置默认为空
        QueryIndicatorParam queryIndicatorParam = new QueryIndicatorParam();
        queryIndicatorParam.setPageNum(1);
        // 分页查询参数
        queryIndicatorParam.setPageSize(PAGE_SIZE);
        queryIndicatorParam.setIndicatorName(ObjectUtil.defaultIfNull(indicatorName, ""));
        queryIndicatorParam.setIndicatorType(ObjectUtil.defaultIfNull(indicatorType, ""));
        queryIndicatorParam.setCategory(ObjectUtil.defaultIfNull(category, ""));

        // 导出参数，标题，sheet页
        ExportParams exportParams = new ExportParams("度量指标", "度量指标");
        Workbook workbook;

        // 查询数据
        workbook = ExcelExportUtil.exportBigExcel(exportParams, IndicatorExportModel.class, indicatorExportServer, queryIndicatorParam);
        writeToHttpResponse(response, workbook);
    }

    /**
     * 写入响应
     *
     * @param response 响应
     * @param workbook excel文件流
     */
    private void writeToHttpResponse(HttpServletResponse response, Workbook workbook) {
        try {
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            LOGGER.error("write to response stream error, {}", e.getMessage());
            throw new JsonException(500, "内部错误");
        }
    }
}
